<?php
require_once ROOT_LIBRARY_UTILITY.DS.'BaseController.php';
require_once ROOT_LIBRARY_UTILITY.DS.'Globals.php';
require_once ROOT_APPLICATION_MODULE_BACKEND_MODELS.DS. 'Model_Account.php';

class Backend_AuthController extends BaseController
{

    public function init(){
        parent::init();
        $this->_helper->layout->setLayout('backend');
    }

    public function  preDispatch() {
        
    }

    public function indexAction()
    {

    }


    public function loginAction()
    {
    	try
    	{
            $this->view->action = 'login';

            if ($this->_request->isPost()) {
                $username = trim($this->_request->getPost('txtUserName'));
                $password = md5(trim($this->_request->getPost('txtPassword')));
                $language = trim($this->_request->getPost('selLanguage'));
                $securityCode = trim($this->_request->getPost('txtSecurityCode'));


                if (empty($username)) {
                    $this->view->errMsg = $this->view->lang_data->_('Please provide a username.');
                } else {
                    // setup Zend_Auth adapter for a database table
                    Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
                    $authAdapter = new Zend_Auth_Adapter_DbTable($this->_db,'accounts','username','password');

                    
                    // Set the input credential values to authenticate against
                    $authAdapter->setIdentity($username);
                    $authAdapter->setCredential($password);

                    // do the authentication
                    $auth = Zend_Auth::getInstance();
                    $result = $auth->authenticate($authAdapter);
                    if ($result->isValid()) {
                        //set Session Language
                        $lang = new Zend_Session_Namespace('language');
                        $lang->type = $language;

                        // success : store database row to auth's storage system
                        // (not the password though!)
                        $data = $authAdapter->getResultRowObject(null, 'password');
                        if($data->active == ACTIVE)
                        {
                            $auth->getStorage()->write($data);
                            if($data->account_types_id == ADMIN)
                                $this->_redirect('/backend/account');
                            else
                                $this->_redirect ('/backend/customer');
                        }
                        else
                            $this->view->errMsg = $this->view->lang_data->_("User is not active");

                    } else {
                        // failure: clear database row from sessionz
                        // get the type of authentication failure
                        switch ($result->getCode())
                        {
                            //"Identity(login_name) not found" case
                            case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
                                 $this->view->errMsg = $this->view->lang_data->_("Account isn't existed.");
                                break;
                            //"Identity and Credential(passwd) do not match" case
                            case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                                 $this->view->errMsg = $this->view->lang_data->_('Username and Password do not match.');
                                break;
                            default:
                                $this->view->errMsg = $this->view->lang_data->_('Login failed.');
                            break;
                        }
                    }
                }
            }
            elseif($this->_request->getMethod()=='GET')
            {
                $paramLang = $this->_request->getParam('lang');
                Globals::setLanguage($paramLang);
                Globals::getLanguage($this);

                if(Zend_Auth::getInstance()->hasIdentity())
                {
                    if($this->view->user->account_types_id == ADMIN)
                        $this->_redirect ('/backend/account');
                    else
                        $this->_redirect ('/backend/customer');
                }
            }
    	}
    	catch (Exception  $ex)
    	{
            $this->view->errMsg = $ex->getMessage();
    	}
    }


    public function logoutAction()
    {
       	$auth = Zend_Auth::getInstance();
        $auth->setStorage(new Zend_Auth_Storage_Session("back"));
        Zend_Session::destroy();
        $this->_redirect('/backend/auth/login');
    }


    public function changepwAction()
    {
        $this->view->title = $this->view->lang_data->_("Change password");

        if ($this->_request->getMethod()== 'POST') {
            $mdAccount 		= new Model_Account();
            $user = $mdAccount->_getByKey($this->view->user->id);

            // request param
            $curent_pass 	= trim($this->_request->getPost('txtCurrentPass')) ;
            $new_pass 		= trim($this->_request->getPost('txtNewPass')) ;
            $confirm_pass 	= trim($this->_request->getPost('txtConfirmPass')) ;
            
            if (($curent_pass == '') || ($curent_pass == '') || ($curent_pass == ''))
            {
                $this->view->errMsg = $this->view->lang_data->_("Required field cannot be left blank");
            }
            else if (md5($curent_pass) !== $user->password)
            {
                $this->view->errMsg = $this->view->lang_data->_("The password you gave is incorrect.");
            }
            else if ($new_pass != $confirm_pass)
            {
                $this->view->errMsg = $this->view->lang_data->_("Passwords do not match.");
            }else{
                $user->password = md5($new_pass);
                $mdAccount->_update($user);
                $this->_redirect('/backend/account');
            }
        }
        elseif($this->_request->getMethod()=='GET')
        {
            $paramLang 		= $this->_request->getParam('lang');
            Globals::setLanguage($paramLang);
            Globals::getLanguage($this);
        }
    }


}